import { ResourceTransformer } from '../transformers/ResourceTransformer';
import { VirtualFileSystem } from '../../../../../../../pages/editor/store/VirtualFileSystem';
import { FileSystemNode, DirectoryInfo, FileInfo } from '../../types';
import { SearchMode } from '../../../../../../../pages/editor/store/VirtualFileSystem';

export interface AIContext {
  currentFile: {
    path: string;
    content: any;
    type: string;
  };
  projectStructure: FileSystemNode[];
  relatedFiles: {
    path: string;
    content: any;
    type: string;
    relevance: number;
  }[];
  dependencies: string[];
  code?: string;
  prompt?: string;
  metadata?: {
    resourceType: string;
    dependencies?: string[];
    schema?: any;
  };
}

export interface AIContextGenerator {
  getContext: (path: string, content: any) => Promise<AIContext>;
}

export class DefaultAIContextGenerator implements AIContextGenerator {
  private transformer: ResourceTransformer;
  private vfs: VirtualFileSystem;

  constructor(transformer: ResourceTransformer, vfs: VirtualFileSystem) {
    this.transformer = transformer;
    this.vfs = vfs;
  }

  getContext = async (path: string, content: any): Promise<AIContext> => {
    console.log('[VFS AIContextGenerator] 开始生成上下文:', path);

    const fileType = this.getFileType(path);
    const projectStructure = (await this.vfs.getDirTree('/', {
      includeTypeEntity: true,
      recursive: true,
    })) as FileSystemNode[];
    const dependencies = await this.vfs.getDependencies(path);
    const relatedFiles = await this.findRelatedFiles(path, content);

    // 获取原有的上下文信息
    const resourceType = this.transformer.getResourceTypeByPath(path);
    const code = await this.transformer.transformToCode(path, content);

    const context: AIContext = {
      currentFile: {
        path,
        content,
        type: fileType,
      },
      projectStructure,
      relatedFiles,
      dependencies: dependencies.map((dep) => dep.path),
      code,
      prompt: this.getPrompt(resourceType.type),
      metadata: {
        resourceType: resourceType.type,
        dependencies: await this.getDependencies(path),
        schema: await this.getSchema(resourceType.type),
      },
    };

    console.log('[VFS AIContextGenerator] 上下文生成完成:', {
      path,
      relatedFilesCount: relatedFiles.length,
      dependenciesCount: dependencies.length,
    });

    return context;
  };

  private getFileType(path: string): string {
    const extension = path.split('.').pop() || '';
    return extension.toLowerCase();
  }

  private async findRelatedFiles(path: string, content: any): Promise<AIContext['relatedFiles']> {
    const relatedFiles: AIContext['relatedFiles'] = [];

    // 1. 添加依赖文件
    const dependencies = await this.vfs.getDependencies(path);
    for (const dep of dependencies) {
      const file = await this.vfs.readFile(dep.path);
      if (file) {
        relatedFiles.push({
          path: dep.path,
          content: file.content,
          type: this.getFileType(dep.path),
          relevance: 1,
        });
      }
    }

    // 2. 添加同目录下的相关文件
    const dir = path.substring(0, path.lastIndexOf('/'));
    const dirFiles = await this.vfs.readdir(dir);
    for (const file of dirFiles) {
      if (typeof file === 'string' && file !== path) {
        const fileContent = await this.vfs.readFile(file);
        if (fileContent) {
          relatedFiles.push({
            path: file,
            content: fileContent.content,
            type: this.getFileType(file),
            relevance: 0.8,
          });
        }
      }
    }

    // 3. 使用语义搜索找到相关文件
    const searchResults = await this.vfs.search(JSON.stringify(content), {
      mode: SearchMode.SEMANTIC,
      maxResults: 5,
    });

    console.log('[VFS AIContextGenerator] 语义搜索结果:', searchResults);

    for (const result of searchResults) {
      if (
        result.item.metadata.path !== path &&
        !relatedFiles.some((f) => f.path === result.item.metadata.path)
      ) {
        const file = await this.vfs.readFile(result.item.metadata.path);
        if (file) {
          relatedFiles.push({
            path: result.item.metadata.path,
            content: file.content,
            type: this.getFileType(result.item.metadata.path),
            relevance: result.score || 0.5,
          });
        }
      }
    }

    // 按相关性排序
    return relatedFiles.sort((a, b) => b.relevance - a.relevance);
  }

  private getPrompt(resourceType: string): string {
    // TODO: 根据资源类型返回合适的提示
    return '';
  }

  private async getDependencies(path: string): Promise<string[]> {
    const dependencies = await this.vfs.getDependencies(path);
    return dependencies.map((dep) => dep.path);
  }

  private async getSchema(resourceType: string): Promise<any> {
    // TODO: 根据资源类型返回对应的 schema
    return null;
  }

  async suggestCodeChanges(path: string): Promise<CodeSuggestion[]> {
    // TODO: 实现代码建议功能
    return [];
  }
}

interface CodeSuggestion {
  path: string;
  changes: {
    type: 'add' | 'remove' | 'modify';
    content: string;
    line?: number;
  }[];
  explanation: string;
  confidence: number;
}
